Source Code Viewer - Example 3 - BrowserTabInterceptor2

package name.matthewgreet.example3.common;



import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;


/**
 * If the action implements BrowserTabAware, sets tab id from cookies.  The requesting web page must be set up for this 
 * to be correct.  See {@link ServletLibrary#getBrowserTabId}.
 *   
 * <H3>Interceptor parameters</H3>
 * <DL>
 * </DL>
 * 
 * <H3>Extending the interceptor</H3>
 * <P>The following methods can be overridden :-</P>
 * <DL>
 * <DT>attributeCloneAction</DT><DD>Whether to ignore, copy or clone a tab-specific attribute of the old tab.</DD>
 * <DT>attributeFromOldTabToNewClone</DT><DD>Clones a private, tab-specific attribute from the old tab to the new.</DD>
 * <DT>attributeFromOldTabToNewCopyConstructor</DT><DD>Copies a private, tab-specific attribute from the old tab to the 
 *                                                     new using the copy constructor.</DD>
 * <DT>attributeFromOldTabToNewCopyReference</DT><DD>Copies reference to a private, tab-specific attribute from the old 
 *                                                   tab to the new.</DD>
 * <DT>attributeFromOldTabToNewIgnore</DT><DD>Notification that a private, tab-specific attribute found in the old tab 
                                              will not be copied.</DD>
 * <DT>attributeFromOldTabToNewNull</DT><DD>Copies null value of a private, tab-specific attribute from the old tab to 
 *                                          the new.</DD>
 * <DT>attributesFromOldTabToNewTab</DT><DD>Copies private, tab-specific attributes from the old tab to the new by 
 *                                          various means.</DD>
 * </DL>
 * 
 * <H3>Example code</H3>
 * <PRE>
 * &#064;InterceptorRefs({
 *   &#064;InterceptorRef(value="browserTab2"),
 *   &#064;InterceptorRef(value="defaultStack")
 *})
 * </PRE>
 */
public class BrowserTabInterceptor2 extends AbstractInterceptor {
    public enum AttributeCloneAction {CLONE, COPY_CONSTRUCTOR, COPY_REFERENCE, IGNORE, NULL}
    
    private static final long serialVersionUID = -1555224920319813415L;
    
    private static final String ATTR_NAME_TAB_ID_COOKIE =  BrowserTabInterceptor2.class.getName() + "_TabIdCookie";
    
    /**
     * Returns what to do with existing attributes of an existing page if the user is opening a hyperlink in a new 
     * browser tab.
     */
    protected AttributeCloneAction attributeCloneAction(BrowserTabAware2 browserTabAware, ActionInvocation invocation,
			String attributeName, Object attributeValue) {
		Class<?> valueClass;
		
    	if (attributeValue == null) {
    		return AttributeCloneAction.NULL;
    	}
		valueClass = attributeValue.getClass();
		try {
			valueClass.getConstructor(valueClass);
	        return AttributeCloneAction.COPY_CONSTRUCTOR;
		}
		catch (NoSuchMethodException | SecurityException e) {
			// Ignore;
		}
    	if (attributeValue instanceof Cloneable) {
            return AttributeCloneAction.CLONE;
    	}
        return AttributeCloneAction.COPY_REFERENCE;
	}

    /**
	 * Handles an attribute from the old tab that should be cloned and returns whether it succeeded.
	 */
	protected boolean attributeFromOldTabToNewTabClone(BrowserTabAware2 browserTabAware, ActionInvocation invocation,
			BrowserTabSession oldBrowserTabSession, BrowserTabSession newBrowserTabSession, Entry<String,Object> oldAttributeEntry) {
		Method cloneMethod;
		
		if (oldAttributeEntry.getValue() instanceof Cloneable) {
			try {
				cloneMethod = oldAttributeEntry.getValue().getClass().getMethod("clone");
				newBrowserTabSession.setAttribute(oldAttributeEntry.getKey(), cloneMethod.invoke(oldAttributeEntry.getValue()));
				return true;
			}
			catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
				return false;
			}
		} else {
			return false;
		}
	}
	
	/**
	 * Handles an attribute from the old tab that that should be copied with a copy constructor and returns whether it 
	 * succeeded.
	 */
	protected boolean attributeFromOldTabToNewTabCopyConstructor(BrowserTabAware2 browserTabAware, ActionInvocation invocation,
			BrowserTabSession oldBrowserTabSession, BrowserTabSession newBrowserTabSession, Entry<String,Object> oldAttributeEntry) {
		Class<?> valueClass;
		Constructor<?> copyConstructor;
		Object newValue;
		
		try {
			valueClass = oldAttributeEntry.getValue().getClass();
			copyConstructor = valueClass.getConstructor(valueClass);
			newValue = copyConstructor.newInstance(oldAttributeEntry.getValue());
			newBrowserTabSession.setAttribute(oldAttributeEntry.getKey(), newValue);
			return true;
		}
		catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			return false;
		}
	}

	/**
	 * Handles an attribute from the old tab that where its reference should be copied and returns whether it succeeded.
	 */
	protected boolean attributeFromOldTabToNewTabCopyReference(BrowserTabAware2 browserTabAware, ActionInvocation invocation,
			BrowserTabSession oldBrowserTabSession, BrowserTabSession newBrowserTabSession, Entry<String,Object> oldAttributeEntry) {
		newBrowserTabSession.setAttribute(oldAttributeEntry.getKey(), oldAttributeEntry.getValue());
		return true;
	}

	/**
	 * Handles an attribute from the old tab that should be ignored and returns whether it succeeded, which does nothing.
	 */
	protected boolean attributeFromOldTabToNewTabIgnore(BrowserTabAware2 browserTabAware, ActionInvocation invocation,
			BrowserTabSession oldBrowserTabSession, BrowserTabSession newBrowserTabSession, Entry<String,Object> oldAttributeEntry) {
		// Does nothing
		return true;
	}

	/**
	 * Handles an attribute from the old tab that that has a null value and returns whether it succeeded.
	 */
	protected boolean attributeFromOldTabToNewTabNull(BrowserTabAware2 browserTabAware, ActionInvocation invocation,
			BrowserTabSession oldBrowserTabSession, BrowserTabSession newBrowserTabSession, Entry<String,Object> oldAttributeEntry) {
		newBrowserTabSession.setAttribute(oldAttributeEntry.getKey(), oldAttributeEntry.getValue());
		return true;
	}

	/**
     * Called when the user's web browser reloads because the page has been opened in a new tab, to copy private, 
     * tab-specific attributes from the old tab to the new.
     */
	protected void attributesFromOldTabToNewTab(BrowserTabAware2 browserTabAware, ActionInvocation invocation,
			BrowserTabSession oldBrowserTabSession, BrowserTabSession newBrowserTabSession) {
		AttributeCloneAction attributeCloneAction;
		Map<String,Object> oldPrivateMap, newPrivateMap;
		Set<String> attributeFailures, attributeIgnores;
		String oldAttributeName;
		boolean success;
		
		attributeFailures = new HashSet<>();
		attributeIgnores = new HashSet<>();
		browserTabAware.copyAttributesFromOldTabToNewTab(oldBrowserTabSession, newBrowserTabSession, attributeIgnores, attributeFailures);
		oldPrivateMap = oldBrowserTabSession.getPrivateAttributeMap();
		newPrivateMap = newBrowserTabSession.getPrivateAttributeMap();
		for (Entry<String,Object> oldAttributeEntry: oldPrivateMap.entrySet()) {
			oldAttributeName = oldAttributeEntry.getKey();
			if (!attributeIgnores.contains(oldAttributeName) && !newPrivateMap.containsKey(oldAttributeName)) {
				attributeCloneAction = attributeCloneAction(browserTabAware, invocation, oldAttributeName, oldAttributeEntry.getValue());
				success = true;
				switch (attributeCloneAction) {
				case CLONE:
					success = attributeFromOldTabToNewTabClone(browserTabAware, invocation, oldBrowserTabSession, newBrowserTabSession, oldAttributeEntry);
					break;
				case COPY_CONSTRUCTOR:
					success = attributeFromOldTabToNewTabCopyConstructor(browserTabAware, invocation, oldBrowserTabSession, newBrowserTabSession, oldAttributeEntry);
					break;
				case COPY_REFERENCE:
					success = attributeFromOldTabToNewTabCopyReference(browserTabAware, invocation, oldBrowserTabSession, newBrowserTabSession, oldAttributeEntry);
					break;
				case IGNORE:
					success = attributeFromOldTabToNewTabIgnore(browserTabAware, invocation, oldBrowserTabSession, newBrowserTabSession, oldAttributeEntry);
					break;
				case NULL:
					success = attributeFromOldTabToNewTabNull(browserTabAware, invocation, oldBrowserTabSession, newBrowserTabSession, oldAttributeEntry);
					break;
				}
				if (!success) {
					attributeFailures.add(oldAttributeName);
				}
			}
		}
		browserTabAware.handleAttributeFailures(oldBrowserTabSession, newBrowserTabSession, attributeFailures);
	}

    protected String getTabId(ActionInvocation invocation) {
    	Cookie newCookie;
        Cookie[] cookies;
        HttpServletRequest request;
        HttpServletResponse response;
    	String result;
    	
    	request = invocation.getInvocationContext().getServletRequest();
        cookies = request.getCookies();
    	result = ServletLibrary.getBrowserTabId(cookies);
        result = (result != null)?result:"";
        if (result.length() == 0) {
        	newCookie = (Cookie)request.getSession().getAttribute(ATTR_NAME_TAB_ID_COOKIE);
            if (newCookie == null) {
            	newCookie = ServletLibrary.makeSetTabIdCookie();
            	request.getSession().setAttribute(ATTR_NAME_TAB_ID_COOKIE, newCookie);
            }
        	response = invocation.getInvocationContext().getServletResponse();
        	response.addCookie(newCookie);
        	result = newCookie.getValue();
        }
        return result;
    }
    
	@Override
    public String intercept(ActionInvocation invocation) throws Exception {
    	BrowserTabAware2 browserTabAware;
    	BrowserTabSession browserTabSession, oldBrowserTabSession;
        HttpServletRequest request;
        Cookie[] cookies;
        String result, cookieValue, oldCookieValue;
    	
        if (invocation.getAction() instanceof BrowserTabAware2) {
            request = invocation.getInvocationContext().getServletRequest();
            cookies = request.getCookies();
            cookieValue = getTabId(invocation);
            oldCookieValue = ServletLibrary.getBrowserOldTabId(cookies);
            oldCookieValue = (oldCookieValue != null)?oldCookieValue:"";
            browserTabSession = new BrowserTabSessionImpl(invocation.getInvocationContext().getServletRequest().getSession(), cookieValue);
            browserTabAware = (BrowserTabAware2)invocation.getAction();
            if (oldCookieValue.length() > 0 && !oldCookieValue.equals(cookieValue)) {
            	oldBrowserTabSession = new BrowserTabSessionImpl(invocation.getInvocationContext().getServletRequest().getSession(), oldCookieValue);
            	attributesFromOldTabToNewTab(browserTabAware, invocation, oldBrowserTabSession, browserTabSession);
            }
            browserTabAware.setBrowserTabSession(browserTabSession);
        }
        result = invocation.invoke();
        return result;
    }

}